﻿using AddressBooks.Entities;
using AddressBooks.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Collections;
using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace AddressBooks.ViewModel;

public partial class ContactsOrgViewModel : ObservableObject, ICrumbsBar
{
    //[ObservableProperty]
    //private List<Org> dataList = new();
    public ManualObservableCollection<Org> DataList { get; set; } = new();
    [ObservableProperty]
    private Org? selectedOrg;
    [ObservableProperty]
    private string? autoCompText;
    [ObservableProperty]
    private Org? selectedParentOrg;
    partial void OnAutoCompTextChanged(string? value)
    {
        Debug.WriteLine($"Name has changed to {value}");
        _ = FilterItemsAsync(value);
    }
    public ManualObservableCollection<Org> Items { get; set; } = new();

    private async Task FilterItemsAsync(string key)
    {
        if (key == "")
            return;
        Items.CanNotify = false;
        var _orgs = await service.GetListAsync();

        Items.Clear();

        foreach (var data in _orgs)
        {
            if (data.Name.Contains(key))
            {
                Items.Add(data);
                // FIXME:自动选择
                if (data.Name.Equals(key) && SelectedOrg !=null)
                {
                    SelectedOrg.ParentId = Convert.ToInt16(data.Id);
                }
            }
        }

        Items.CanNotify = true;
    }

    /// <summary>
    /// 触发信息修改命令
    /// </summary>
    [RelayCommand]
    private async Task ModifyOrgInfo()
    {
        var i = await service.AsUpdateable(SelectedOrg).ExecuteCommandAsync();
        if (i == 1)
        {
            Growl.Success("更新成功");
            await GetTree(true);
        }
        else Growl.Warning("更新失败");
    }
    /// <summary>
    /// 触发信息删除命令
    /// </summary>
    [RelayCommand]
    private async Task DeleteOrg()
    {
        await Task.Run(() => Debug.WriteLine(SelectedParentOrg?.Name));
        if (SelectedOrg?.Children?.Count > 0)
        {
            Growl.Info("只能删除末级单位.");
            return;
        }
        if (SelectedOrg?.Count > 0)
        {
            var res = HandyControl.Controls.MessageBox.Show(
                "本单位下还有人员，是否确定删除？", "确认",
                MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (res == MessageBoxResult.Yes)
            {
                PublicContactsManager publicContactsManager = new();
                var resN = await publicContactsManager.AsUpdateable().SetColumns(it=>it.Active == 0)
                    .Where(it=>it.Orgid == SelectedOrg.Id).ExecuteCommandAsync();
                if (resN > 0)
                {
                    Growl.Success($"成功删除{resN}条记录");
                }
            }
            else
            {
                Growl.Error("有内鬼，中止交易");
                return;
            }
        }
        Growl.Warning("信息删除中....");
        var i = await service.AsDeleteable()
            .Where(it => it.Id == SelectedOrg!.Id)
            .ExecuteCommandAsync();
        if (i == 1)
        {
            Growl.Success("删除成功");
            var r = from d in DataList
                    where d.Id == SelectedOrg!.ParentId
                    select d;
            var root = r.First();
            var ok = root?.Children?.Remove(SelectedOrg!);
            if ( ok == true) Growl.Success("OK");
            await GetTree(true);
        }
        else Growl.Warning("删除失败");
    }

    /// <summary>
    /// 触发入库处理命令
    /// </summary>
    [RelayCommand]
    private async Task AllChildAddDB()
    {
        var addOrgs = SelectedOrg?.Children?.Where(it => it.Id == 0).ToList();
        if (addOrgs == null)
        {
            Growl.Info("无可添加的内容");
            return;
        }
        try
        {
            bool ok = await service.AddNewOrgsToDb(addOrgs);
            if (!ok)
            {
                Growl.Warning("入库失败");
                return;
            }
            Growl.Ask("入库成功，是否立即刷新单位代码？", isConfirmed =>
            {
                if (isConfirmed)
                {
                    // 更新通讯录的单位ID
                    var i = ContactsManager.UpdateOrgId();
                    Growl.Info($"更新通讯录中 {i} 条记录");
                    // 更新计数
                    i = OrgManager.UpdateOrgCount();
                    Growl.Info($"更新 {i} 条记数记录");
                }
                return true;
            });
        }
        catch (Exception e)
        {
            Growl.Error("出现不可思议的错误：" + e.Message);
        }
    }
    /// <summary>
    /// 触发项目被选择后的处理命令
    /// </summary>
    [RelayCommand]
    private async Task SelectedItemChanged(object sender)
    {
        if (sender is Org o)
        {
            SelectedOrg = o;
            var orgs = await service.GetListAsync();
            SelectedParentOrg = orgs.FirstOrDefault(it => it.Id == o.ParentId);
            AutoCompText = SelectedParentOrg?.Name;
        }
    }
    /// <summary>
    /// 查找需要显示的项目
    /// </summary>
    /// <param name="parentContainer"></param>
    /// <param name="item"></param>
    /// <returns></returns>
    private TreeViewItem FindTreeViewItem(TreeViewItem parentContainer, object item)
    {
        if (parentContainer.Header == item)
        {
            return parentContainer;
        }
        //若没有找到当前节点，则依次查找当前节点的子节点
        foreach (object childItem in parentContainer.Items)
        {
            TreeViewItem childContainer = parentContainer.ItemContainerGenerator.ContainerFromItem(childItem) as TreeViewItem;
            TreeViewItem resultContainer = FindTreeViewItem(childContainer, item);
            if (resultContainer != null)
            {
                return resultContainer;
            }
        }
        return null;
    }
    /// <summary>
    /// 选择需要显示的项目
    /// </summary>
    /// <param name="item"></param>
    /// object item = //要选择的节点
    /// SelectTreeViewItem(item);
    //private void SelectTreeViewItem(object item)
    //{
    //    //找到TreeViewItem控件
    //    TreeViewItem tvi = FindTreeViewItem(MyTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem, item);
    //    if (tvi != null)
    //    {
    //        //设置TreeViewItem控件选中
    //        tvi.IsSelected = true;
    //    }
    //}
    /// <summary>
    /// 触发获取项目树的处理命令
    /// </summary>
    [RelayCommand]
    private async Task GetTree(bool isRefresh = false)
    {
        var list = await service.GetTreeAsync(isRefresh);
        if (list != null)
        {
            //var emptyOrgs = await service.GetEmptyOrg();
            //if (emptyOrgs != null)
            //{
            //    emptyOrgs = emptyOrgs.Select(it => new Org()
            //    { Id = it.Id, Name = it.Name, Count = 0, ParentId = it.ParentId }
            //    ).ToList();
            //    list.Add(new()
            //    {
            //        Id = 90,
            //        ParentId = 0,
            //        Name = "未入库",
            //        Remark = "在通讯录中但未记录在单位表中的列表",
            //        Children = emptyOrgs
            //    });
            //}
            DataList.Clear();
            DataList.CanNotify = false;
            try
            {
                list.ForEach(d =>
                {
                    DataList.Add(d);
                });
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return;
            }
            DataList.CanNotify = true;
        }
    }
    #region 地址栏处理函数
    /// <summary>
    /// 触发面包屑左键点击命令
    /// </summary>
    [RelayCommand]
    public void CrumbsBarLeftButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public void CrumbsBarRightButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public void CrumbsBarDownButtonClick()
    {
        throw new NotImplementedException();
    }

    [RelayCommand]
    public Task CrumbsBarRefreshButtonClick() => GetTree(true);

    readonly OrgManager service = new();
    /// <summary>
    /// 触发工具栏搜索命令
    /// </summary>
    [RelayCommand]
    public async Task CrumbsBarSearchAsync(string key)
    {
        try
        {
            Growl.Info(key);
        }
        catch (Exception)
        {

        }
    }
    #endregion
    public ContactsOrgViewModel()
    {
        _ = GetTree();
    }
}

